package com.example.homework

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatTextView

class PercentText @JvmOverloads constructor(context: Context?, attrs:AttributeSet? = null, resId:Int = 0) : AppCompatTextView(context, attrs,resId) {
    private var textLeft: Float = 0f
    private lateinit var m: Paint.FontMetrics
    private var textWidth: Float = 0f
    private var foreRectLeft = 0f
    private var foreRectRight = 0f
    private var baseLineHeight = 0f

    var percent = 0f
        set(value) {
            field = value
            invalidate()
        }

    var needChangeRed = true//是否是要变红的，true的话把本来文字设置成白色的

    override fun onDraw(canvas: Canvas?) {
        setTextColor(if (needChangeRed) Color.WHITE else Color.RED)
        super.onDraw(canvas)
        calSize()
//        drawBackText(canvas)
        drawForeText(canvas)
    }

    private fun drawForeText(canvas: Canvas?) {
        canvas?.let {
            paint.color = if (needChangeRed) Color.RED else Color.WHITE
            it.clipRect(foreRectLeft,0f,foreRectRight,height.toFloat())
            it.drawText(text.toString(),textLeft,baseLineHeight,paint)
        }
    }

    private fun calSize() {
        textWidth = paint.measureText(text.toString())
        textLeft = (width-textWidth)/2
        foreRectLeft = 0f
        foreRectRight = textLeft + textWidth*percent

        m = paint.fontMetrics
//        baseLineHeight = height/2-m.descent+(m.descent-m.ascent)/2     //用这个计算，和textView自己居中的，有一点点偏离
        baseLineHeight = height/2-m.bottom+(m.bottom-m.top)/2
    }

}